import 'package:flutter/material.dart';
import 'package:flutter_smart_heating/common/app.dart';
import 'package:flutter_smart_heating/common/http.dart';
import 'package:flutter_smart_heating/mode/list_pagination_model.dart';
import 'package:flutter_smart_heating/pages/article/widget/item.dart';
import 'package:flutter_smart_heating/ui/src/pull_to_refresh.dart';
import 'package:flutter_smart_heating/ui/ui.dart';

class ArticlePage extends StatefulWidget {
  const ArticlePage({super.key});

  @override
  State<ArticlePage> createState() => _ArticlePageState();
}

class _ArticlePageState extends State<ArticlePage>
    with SingleTickerProviderStateMixin {
  late TabController tabController;
  List<dynamic> cate = [];
  @override
  void initState() {
    super.initState();
    App.report('/article');
    fetchCate();
  }

  fetchCate() async {
    var res = await Http.instance.post('/plugin/article/api/cate');

    if (res.code == 1) {
      setState(() {
        cate.addAll(res.data);
      });
      tabController = TabController(length: cate.length, vsync: this);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        titleSpacing: 0,
        leadingWidth: 0,
        title: UiPanel(
          width: 300,
          height: 35,
          borderRadius: BorderRadius.circular(30),
          child: cate.isEmpty
              ? Container()
              : TabBar(
                  controller: tabController,
                  isScrollable: false,
                  dividerColor: Colors.transparent,
                  splashBorderRadius: BorderRadius.circular(30),
                  indicatorSize: TabBarIndicatorSize.tab,
                  indicator: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(30),
                    gradient: const LinearGradient(
                      colors: [
                        Color.fromARGB(255, 11, 232, 248),
                        Color.fromARGB(255, 33, 51, 243),
                      ],
                    ),
                  ),
                  indicatorColor: Colors.black,
                  labelColor: Colors.white,
                  unselectedLabelColor:
                      UiTheme(context).matchColor(Colors.black, Colors.white),
                  unselectedLabelStyle: const TextStyle(
                    fontWeight: FontWeight.normal,
                  ),
                  labelStyle: TextStyle(
                    fontWeight: FontWeight.bold,
                    fontSize: UiTheme.fontSize.tabbarFontSize,
                    color: Colors.red,
                  ),
                  tabs: List.generate(
                    cate.length,
                    (index) => Tab(
                      text: cate[index]['name'],
                    ),
                  ),
                ),
        ),
      ),
      body: Column(
        mainAxisSize: MainAxisSize.max,
        children: [
          const SizedBox(height: UiTheme.toolbarSpacing),
          Expanded(
            child: cate.isNotEmpty
                ? TabBarView(
                    controller: tabController,
                    children: List.generate(
                      cate.length,
                      (index) => ArticlePageView(
                        cateId: cate[index]['id'],
                      ),
                    ),
                  )
                : const ArticlePageView(),
          )
        ],
      ),
    );
  }
}

class ArticlePageView extends StatefulWidget {
  const ArticlePageView({super.key, this.cateId});
  final int? cateId;

  @override
  State<ArticlePageView> createState() => _ArticlePageViewState();
}

class _ArticlePageViewState extends State<ArticlePageView>
    with AutomaticKeepAliveClientMixin {
  List<dynamic> list = List.filled(10, {}).toList();
  ListPaginationModel pagination = ListPaginationModel();
  bool refreshing = false;

  @override
  bool get wantKeepAlive => true;
  @override
  void initState() {
    fetchData();

    super.initState();
  }

  fetchData() async {
    if (widget.cateId == null) {
      return;
    }

    var res = await Http.instance.post(
      '/plugin/article/api/index',
      data: {
        "page": pagination.currentPage,
        "cate_id": widget.cateId,
      },
    );

    if (res.code == 1) {
      if (pagination.currentPage <= 1) {
        list.clear();
      }
      pagination = ListPaginationModel.fromJson(res.data);
      res.data['data'].forEach(
        (item) => list.add(item),
      );
    }
    setState(() {});
    refreshController.refreshCompleted();
    if (pagination.hasMore) {
      refreshController.loadComplete();
    } else {
      refreshController.loadNoData();
    }
  }

  RefreshController refreshController = RefreshController();
  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Container(
      clipBehavior: Clip.hardEdge,
      margin: const EdgeInsets.symmetric(horizontal: UiTheme.spacingX),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(UiTheme.boxRadiusX),
      ),
      child: UiPushToRefresh(
        controller: refreshController,
        onRefresh: () {
          pagination.currentPage = 1;
          fetchData();
        },
        enablePullDown: widget.cateId != null,
        enablePullUp: pagination.total > 0 && !refreshController.isRefresh,
        onLoad: () {
          pagination.currentPage++;
          fetchData();
        },
        child: list.isEmpty
            ? const Center(child: UiResult())
            : ListView.separated(
                itemBuilder: (context, index) {
                  var item = list[index];
                  return ArticleItemView(item: item, index: index);
                },
                separatorBuilder: (context, index) => const SizedBox(
                  height: UiTheme.spacingX,
                ),
                itemCount: list.length,
              ),
      ),
    );
  }
}
